using Godot;
using Newtonsoft.Json;
using System;

namespace Box;

public partial class ProjectOpenWindow : FileDialog
{
	public TreeTabContainer TreeTabContainer;
	public override void _Ready()
	{
		FileSelected += _onOpenProject;
	}

	public void _onOpenProject(string path) {
		FileAccess proj_file =FileAccess.Open(path,FileAccess.ModeFlags.Read);
		if(proj_file.IsOpen()) {
			PTProject_JSON setting = JsonConvert.DeserializeObject<PTProject_JSON>(proj_file.GetAsText());

			ProcessTreeEditor.CurrentEditor.OpenProject(setting.project_name,CurrentDir);

			TreeTabContainer.Clear();


			DirAccess trees_dir = DirAccess.Open($"{CurrentDir}/trees");
			trees_dir.ListDirBegin();
			string next = trees_dir.GetNext();
			while(next != "") {
				if(!trees_dir.CurrentIsDir()) {
					FileAccess json_file = FileAccess.Open($"{CurrentDir}/trees/{next}",FileAccess.ModeFlags.Read);
					var edit = ProcessTreeEditorHelper.ReadJson(json_file.GetAsText());
					edit.Init(TreeTabContainer.PropertyPanel);
					TreeTabContainer.AddTab(edit);
				}
				next = trees_dir.GetNext();
			}


		}
	}
}
